package Middleware

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"github.com/syyongx/php2go"
	"hello/services/Action"
	"hello/wl"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego/context"
)

var minCount int
func init()  {
	confMinCount:=wl.C("minCount")
	minCount, _ =strconv.Atoi(confMinCount)
}

func getClientIP(ctx *context.Context) string {
	ip := ctx.Request.Header.Get("X-Forwarded-For")
	if strings.Contains(ip, "127.0.0.1") || ip == "" {
		ip = ctx.Request.Header.Get("X-real-ip")
	}

	if ip == "" {
		return "127.0.0.1"
	}

	return ip
}

func Get(ctx *context.Context)  {
	ip:=getClientIP(ctx)
	fmt.Println("真实IP",ip)
	req := ctx.Request
	addr := req.RemoteAddr // "IP:port" "192.168.1.150:8889"
	fmt.Println("IP是",addr)

	addrArr := strings.Split(addr, ":")
	addrKey:="IP"+addrArr[0]

	if php2go.Empty(addrKey){
		fmt.Println("无法获取IP地址!")
	}

	//改为一个小时访问次数
	redis:=wl.WLRedis()

	//记录访问次数
	Action.WriteAjaxCount(redis)


	if !php2go.Empty(redis) {
		redis.PFAdd("blog:api:ip:total",ip)

		redis.HSet("blog:api:ip:list",ip,"1")

		countValue, _ := redis.Get(addrKey).Result()

		countInt,_:=strconv.Atoi(countValue)

		if  countInt!=0 {
			var ipCount int=countInt

			fmt.Println("redis的值",ipCount)

			if ipCount>=minCount{

				ctx.Output.JSON(wl.AjaxClick("操作频率过快!"),true,false)

			}else{
				ipCount++
				fmt.Println("redis++")
				err := redis.Set(addrKey, ipCount, 60*60*time.Second).Err()
				if err != nil {
					panic(err)
				}
			}

		}else{
			fmt.Println("初始化用户访问次数")

			err := redis.Set(addrKey, 1, 60*60*time.Second).Err()
			if err != nil {
				panic(err)
			}
		}








	}


}

func IntToBytes(n int) []byte {
	x := int32(n)
	bytesBuffer := bytes.NewBuffer([]byte{})
	binary.Write(bytesBuffer, binary.BigEndian, x)
	return bytesBuffer.Bytes()
}